import React, { Component, } from 'react';
import { base, toast, } from 'nc-lightapp-front';
const {NCModal, NCButton,} = base;
import SSCUnitGridRef from 'src/ssctp/refer/sscbd/SSCUnitGridRef/index';
import {
  asyncPointGridRef,
} from './async.js'
import './index.less'
import SSCTransfer from './SSCTransfer.js'

class CopyRecord extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dataSource: [], // 左树 数据源
      referValue: {}, // 当前目标共享中心
    }
    this.sourceTreeRef = React.createRef();
  }
  
  // 目标共享中心变化
  referOnChange = ({refpk, refcode}, {display, value}) => this.setState({referValue: {refpk, refcode, refname: display}})

  // 打开复制组件时
  modalEnter = async () => {
    const {
      config: {
        qryUrl, pk_sscunit, from,
      },
      syncTree: {
        createTreeData,
      },
    } = this.props

    const payload = {
      queryCondition: {
        isShowUsual: 'false',
        pk_sscunit,
      },
      pageInfo: {
        pageIndex: '-1',
        pageSize: '10',
      },
    }
    const response = await asyncPointGridRef(payload, qryUrl)

    if (!response || !response.data) return

    const nodes = response.data.rows || response.data.nodes

    for (let item of nodes) {
      item.iconBox = {addIcon: false, editIcon: false, delIcon: false}
    }

    const dataSource = createTreeData(nodes) || []
    
    if (from === 'point') {
      let index = -1
      while(++index < dataSource.length) {
        if (dataSource[index].isleaf) dataSource[index] = null
      }
      this.setState({dataSource: dataSource.filter(node => !!node)})
    } else if (from === 'problem') {
      if (dataSource[0].children) {
        let index = -1
        while(++index < dataSource[0].children.length) {
          if (dataSource[0].children[index].isleaf) dataSource[0].children[index] = null
        }
        dataSource[0].children = dataSource[0].children.filter(node => !!node)
        this.setState({dataSource})
      } else {
        this.setState({dataSource: []})
      }
    }

    this.sourceTreeRef.current.initSourceTree()
  }

  // 取消复制
  copyCancel = () => {
    this.setState({
      referValue: {},
    })
    this.sourceTreeRef.current.reset()
    this.props.config.Cancel()
  }

  // 关闭组件
  copyOnHide = () => {
    this.sourceTreeRef.current.reset()
    this.props.config.onHide()
  }

  // 确认复制
  copySure = () => {
    const {
      state: { referValue: { refpk, }, },
      props: { config: { Sure, pkToastTxt, keysToastTxt, onHide}, },
    } = this

    const targetKeys = this.sourceTreeRef.current.getTargetKeys()
    
    if (!refpk) {
      if (pkToastTxt) {
        return toast({ title: pkToastTxt, duration: 5, color: 'warning'})
      }
      return console.warn('请选择目标共享中心')
    } else if (!targetKeys.length) {
      if (keysToastTxt) {
        return toast({ title: keysToastTxt, duration: 5, color: 'warning'})
      }
      return console.warn('请选择档案')
    }
    
    this.sourceTreeRef.current.reset()
    Sure(refpk, targetKeys)
    // onHide()
  }

  // 组件重置
  reset = () => this.setState({ dataSource: [], referValue: {}, })

  render() {
    const {
      props: {config},
      state: {
        dataSource,
        referValue,
      },
      referOnChange,
      modalEnter,
      copyCancel,
      copyOnHide,
      copySure,
    } = this

    const {
      show,
      headTitle,
      leftTitle,
      rightTitle,
      sureBtnTxt,
      cancelBtnTxt,
      onEnter,
      placeholder,
    } = config

    const transferProps = { // 穿梭框组件配置
			dataSource,
      titles: [leftTitle || 'leftTitle', rightTitle || 'rightTitle'],
		};

    return (
      <NCModal
        fieldid="CopyRecord"
        show={show} 
        onHide={copyOnHide}
        onEnter={
          () => {
            if (onEnter) {
              onEnter.call(this)
            } else {
              modalEnter()
            }
          }
        }
        id='copy-record--modal'
        size='lg'
        resizable={false}
      >
        <NCModal.Header closeButton={true}>
            <NCModal.Title>{headTitle || 'headTitle'}</NCModal.Title>
        </NCModal.Header>
        <NCModal.Body>
          {/* 目标共享中心 */}
          <div className='area' style={{flex: '0'}}>
            <span class="ssc-must copy-ssc-must">*</span>
            {SSCUnitGridRef({
              onChange: referOnChange,
              disabled: false,
              value: referValue,
              isAlwaysEmitOnChange: true, // 始终触发onChange事件
              // queryCondition: () => ({}),
              fieldid:'SSCUnitGridRef',
              placeholder: placeholder || '',
            })}
          </div>
          {/* 自定义穿梭框 */}
          <div className='area' style={{flex: '1', display: 'flex', flexDirection: 'column'}}>
            <SSCTransfer
              ref={this.sourceTreeRef}
              {...transferProps}
              {...this.props}
            />
          </div>
        </NCModal.Body>
        <NCModal.Footer>
          {/* 确定 */}
          <NCButton fieldid="confirm" colors="primary" onClick={copySure}>{sureBtnTxt}</NCButton>
          {/* 取消 */}
          <NCButton fieldid="cancel" onClick={copyCancel}>{cancelBtnTxt}</NCButton>
        </NCModal.Footer>
      </NCModal>
    )
  }
}

export default CopyRecord